package com.itheima.canal.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TryLockDemo {
    public static void main(String[] args) {

        MyTtryLock mt = new MyTtryLock();
        new Thread(mt, "A").start();
        new Thread(mt, "B").start();

    }
}

class MyTtryLock implements Runnable {

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        String tName = Thread.currentThread().getName();
        System.out.println(tName + "is try lock");
        try {
            if (lock.tryLock(6, TimeUnit.SECONDS)) {
                System.out.println(tName + "i am in lock true");
                System.out.println(tName + "我要睡一会");
                Thread.sleep(5000);
            } else {
                System.out.println(tName + "i am in lock false");
                return;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
    }
}
